package org.jeecg.modules.oms.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.oms.entity.ProductSalesOrder;
import org.jeecg.modules.oms.entity.ProductSalesOrderTransaction;
import org.jeecg.modules.oms.mapper.ProductSalesOrderMapper;
import org.jeecg.modules.oms.mapper.ProductSalesOrderTransactionMapper;
import org.jeecg.modules.oms.service.IProductSalesOrderTransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 成品销售订单交易记录服务实现类
 */
@Slf4j
@Service
public class ProductSalesOrderTransactionServiceImpl extends ServiceImpl<ProductSalesOrderTransactionMapper, ProductSalesOrderTransaction> implements IProductSalesOrderTransactionService {

    @Autowired
    private ProductSalesOrderMapper productSalesOrderMapper;

    @Override
    public List<ProductSalesOrderTransaction> getTransactionListByOrderId(String orderId) {
        return baseMapper.getTransactionListByOrderId(orderId);
    }
    
    @Override
    public List<ProductSalesOrderTransaction> getTransactionByOrderId(String orderId) {
        return baseMapper.getTransactionListByOrderId(orderId);
    }

    @Override
    public IPage<ProductSalesOrderTransaction> getTransactionPageByOrderId(Page<ProductSalesOrderTransaction> page, String orderId) {
        return baseMapper.getTransactionPageByOrderId(page, orderId);
    }

    @Override
    public IPage<ProductSalesOrderTransaction> getTransactionPageList(Page<ProductSalesOrderTransaction> page, ProductSalesOrderTransaction transaction) {
        return baseMapper.getTransactionPageList(page, transaction);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteTransactionByOrderId(String orderId) {
        return baseMapper.deleteTransactionByOrderId(orderId) >= 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addTransaction(ProductSalesOrderTransaction transaction) {
        // 设置交易时间
        if (transaction.getTransactionTime() == null) {
            transaction.setTransactionTime(new Date());
        }
        
        // 获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (loginUser != null && transaction.getTransactionPersonId() == null) {
            transaction.setTransactionPersonId(loginUser.getId());
            transaction.setTransactionPersonName(loginUser.getRealname());
        }
        
        boolean result = save(transaction);
        if (!result) {
            throw new RuntimeException("保存交易记录失败");
        }
        
        // 更新订单已付金额
        try {
            updateOrderPaidAmount(transaction.getOrderId());
        } catch (Exception e) {
            log.error("更新订单已付金额失败，订单ID: {}", transaction.getOrderId(), e);
            throw new RuntimeException("更新订单已付金额失败: " + e.getMessage());
        }
        
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean editTransaction(ProductSalesOrderTransaction transaction) {
        // 检查交易记录是否存在
        ProductSalesOrderTransaction existTransaction = getById(transaction.getId());
        if (existTransaction == null) {
            log.error("编辑交易记录失败，交易记录不存在，ID: {}", transaction.getId());
            return false;
        }
        
        // 获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (loginUser != null) {
            transaction.setUpdateBy(loginUser.getUsername());
            transaction.setUpdateTime(new Date());
        }
        
        // 更新交易记录
        boolean result = updateById(transaction);
        if (!result) {
            log.error("更新交易记录失败，ID: {}", transaction.getId());
            return false;
        }
        
        // 更新订单已付金额
        updateOrderPaidAmount(transaction.getOrderId());
        
        return true;
    }
    
    /**
     * 更新订单已付金额
     * 
     * @param orderId 订单ID
     */
    private void updateOrderPaidAmount(String orderId) {
        try {
            // 获取订单信息
            ProductSalesOrder order = productSalesOrderMapper.selectById(orderId);
            if (order == null) {
                return;
            }
            
            // 计算已付金额
            List<ProductSalesOrderTransaction> transactions = getTransactionListByOrderId(orderId);
            BigDecimal paidAmount = BigDecimal.ZERO;
            
            for (ProductSalesOrderTransaction transaction : transactions) {
                if (transaction.getAmount() != null) {
                    paidAmount = paidAmount.add(transaction.getAmount());
                }
            }
            
            // 更新订单已付金额
            order.setPaidAmount(paidAmount);
            
            // 计算未付金额
            if (order.getTotalAmount() != null) {
                order.setUnpaidAmount(order.getTotalAmount().subtract(paidAmount));
            }
            
            // 根据已付金额判断是否已付清
            if (order.getTotalAmount() != null && 
                order.getPaidAmount() != null && 
                order.getTotalAmount().compareTo(order.getPaidAmount()) <= 0) {
                order.setPayStatus(2); // 已付清
            } else if (order.getPaidAmount() != null && order.getPaidAmount().compareTo(BigDecimal.ZERO) > 0) {
                order.setPayStatus(1); // 部分付款
            } else {
                order.setPayStatus(0); // 未付款
            }
            
            productSalesOrderMapper.updateById(order);
        } catch (Exception e) {
            log.error("更新订单已付金额异常", e);
        }
    }
} 